package com.peng.service.impl;

import com.peng.config.COSConfig;
import com.peng.service.UploadService;
import com.peng.vo.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {
    @Resource
    private COSConfig cosConfig;
    @Resource
    private COSClient cosClient;

    @Override
    public Result upload(MultipartFile file) {
        try {
            InputStream is = new BufferedInputStream(file.getInputStream());
            String pic = UUID.randomUUID().toString().replace("-", "");
            String picName = file.getOriginalFilename();
            assert picName != null;
            String picType = cosConfig.getPrefix() + pic + picName.substring(picName.lastIndexOf("."));
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //设置流的大小
            objectMetadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), picType, is, objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if (putObjectResult.getETag() != null) {
                return Result.success(cosConfig.getUrl()+picType);
            }
        } catch (IOException e) {
            //出现文件异常
            return Result.fail(20000,"上传失败");
        }
        return Result.fail(20000,"上传失败");
    }
}
